package com.base.thread.demo_21;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock {

	private boolean isLock = false;
	
	private int count = 0;
	
	private Thread lockBy = null;
	
	@Override
	public synchronized void lock() {
		
		Thread current = Thread.currentThread();
		//如果有线程获取锁,并且当前线程不是获取锁的线程,则等待
		while (isLock && current != lockBy) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		// 设置isLock为true 标识此时有线程获取到锁
		isLock = true;
		lockBy = current; //设置获取锁的线程
		count ++ ; //设置获取锁的次数
	}
	
	@Override
	public synchronized void unlock() {
		Thread current = Thread.currentThread();
		if (isLock && current == lockBy) {
			count -- ;
			if (count == 0) {
				isLock = false;
				lockBy = null;
				notify();//唤醒其他的线程
			}
		}
		
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
	}

	@Override
	public boolean tryLock() {
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		return false;
	}


	@Override
	public Condition newCondition() {
		return null;
	}

}
